package com.fjwt.gz.province.changchun.encrypt;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.IOException;

/**
 * @RequestParam注解参数解密
 *
 * @author Lee
 * @date 2024-11-22
 */
public class ParameterDecryptFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletRequestWrapper requestWrapper = new HttpServletRequestWrapper(httpRequest) {
            @Override
            public String getParameter(String name) {
                String value = super.getParameter(name);
                if (value != null && !value.isEmpty()) {
                    try {
                        return AesUtil.decrypt(value);
                    } catch (Exception e) {
                        throw new RuntimeException("解密参数失败: " + name, e);
                    }
                }
                return value;
            }

            @Override
            public String[] getParameterValues(String name) {
                String[] values = super.getParameterValues(name);
                if (values != null) {
                    for (int i = 0; i < values.length; i++) {
                        if (values[i] != null && !values[i].isEmpty()) {
                            try {
                                values[i] = AesUtil.decrypt(values[i]);
                            } catch (Exception e) {
                                throw new RuntimeException("解密参数失败: " + name, e);
                            }
                        }
                    }
                }
                return values;
            }
        };

        chain.doFilter(requestWrapper, response);
    }

    @Override
    public void destroy() {

    }
}
